import { FileListViewData } from './FileService.d';
import HttpClient  from '/@/utils/HttpClient'

const api_base_url = 'http://localhost:5168'
const client = new HttpClient({baseURL:api_base_url})

const get_files = async function (dir: string): Promise<FileListViewData> {
    let url = "/api/File/get_files"
    if(dir) {
        url = `${url}?dir=${dir}`
    }
    let rs = await client.get({url: url})
    return rs as FileListViewData
}
const getUploadUrl = function (dir: string) {
    let url = "/api/File/upload"
    if(dir) {
        url = `${api_base_url}${url}?dir=${dir}`
    }
    return url 
}

const upload= function(dir: string, file: File|Blob|FileList) {
    let url = "/api/File/upload"
    if(dir) {
        url = `${url}?dir=${dir}`
    }
    return client.uploadFile({url: url,  onUploadProgress: e=>{
        console.log(e)
    }}, {
        name: "files",
        file
    })
}

const replaceUrl = (name: string) => {
    return name.replaceAll('+', '%2B')
}

const getDownloadUrl = function(fileName: string) {
    let filePath = replaceUrl(fileName)
    return `${api_base_url}/api/File/download?file=${filePath}`
}
const download = function(fileName: string, fuc:(any)) {
    let filePath = replaceUrl(fileName)
    let url = `${api_base_url}/api/File/download?file=${filePath}`
    client.download(url, fuc)
}
const getFileText = function(fileName: string) : Promise<string> {
    var url = getDownloadUrl(fileName)
    return new Promise((resolve, reject) => {
    fetch(url)
        .then(x => x.text()
            .then(r => resolve(r) ))
        .catch((e: Error)=>reject(e))
    })
}
const delFiles = async (files:string[]) => {
    let api_url = "/api/File/delete"
    await client.post({url: api_url, data: files})
}

const rename = async (dir: string, old: string, newName: string) => {
    let api_url = "/api/File/rename"
    let data = {
        dir,
        oldName: old,
        newName
    }
    await client.post({url: api_url, data })
}


export default {
    get_files,
    upload,
    getUploadUrl,
    getDownloadUrl,
    download,
    getFileText,
    delFiles,
    rename
}